// packageC/pages/takeoutDetail/takeoutDetail.js
const app = getApp()
const common = require('../../../public.js')

Page({
    /**
     * 页面的初始数据
     */
    data: {
        allAttrValueList:[],
        orderList: ['评价', '商家'],
        actIndex: 0,
        bannerList: [],
        active: 0,
        scroll_height: 0,
        scrollh: 0,
        itemId: '',
        height: '',
        showImg: false,
        heightShow: false,
        totalPrice: 0,
    },
    click_album(e){
        let currentIndex = e.currentTarget.dataset.index
        wx.navigateTo({
          url: '/packageA/pages/photoAlbum/photoAlbum?arr='+ JSON.stringify(this.data.shopInfo.backUpPicList) 
           + '&currentIndex=' + currentIndex
          ,
        })
     },
    checkAddress() { //点击地址按钮
        if (!this.data.shopInfo.store.xpoint || !this.data.shopInfo.store.ypoint) {
            common.showToast('商家未设置位置信息')
            return
        }
        let lon = parseFloat(this.data.shopInfo.store.xpoint)
        let lat = parseFloat(this.data.shopInfo.store.ypoint)
        wx.openLocation({
            latitude: lat,
            longitude: lon,
            name: this.data.shopInfo.store.name ? this.data.shopInfo.store.name : null,
            address: this.data.shopInfo.store.address ? this.data.shopInfo.store.address : null,
            scale: 18,
            fail: () => {
                wx.showToast({
                    title: '无地址信息',
                    icon: 'none'
                })
            }
        })
    },
    // 电话
    callPhone() {
        wx.makePhoneCall({
            phoneNumber: this.data.shopInfo.store.mobile,
            fail: function () { }
        })
    },
    closeAddCart() {
        this.setData({
            guigeShow: false
        })
    },
    // 添加购物车

    submitAddCart() {
        const that = this
        const num = this.data.goodsCount
        const itemId = this.data.itemId
        if (!num) {
            common.showToast('没有添加数量')
            return
        }
        console.log('suoyoushuj---',that.data.allAttrValueList);
        // < checkedAttr that.data.allAttrValueList
        var checkedStr = '';
        for(var i = 0;i < that.data.allAttrValueList.length;i++){
            var twoList = that.data.allAttrValueList[i];
            for(var j =0;j < twoList.attrValueList.length;j++){
                if(twoList.attrValueList[j].select == true){
                    checkedStr = checkedStr + twoList.attrValueList[j].attrValue + '/'
                }
              
            }
        }
        let tempJson = {
            // dishFlavor: that.data.checkedAttr,
            dishFlavor:checkedStr?checkedStr.slice(0, -1):'',
            userId: that.data.userInfo.id,
            token: that.data.token,
            itemId,
            num
        }
        common.wxRequest('/cart/add', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                that.closeAddCart()
                that.getCartNum()  //获取
 
                that.setData({
                    goodsCount: 1,
                })
                wx.showToast({
                    title: '添加成功!',
                })
            } else {
                wx.showToast({
                    icon: 'loading',
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },



    // 商品规格
    // clickGetDishAttrList(e) {
    //     let that = this
    //     let { id, item } = e.currentTarget.dataset
    //     let tempJson = {
    //         itemId: id,

    //     }
    //     that.setData({
    //         itemId: id,
    //         goodsNei: item
    //     })
    //     common.post("/item/getDishAttrList", tempJson, function (res) {
    //         let checkedStr = '';

    //         for (let i = 0; i < res.data.length; i++) {
    //             if (i !== res.data.length - 1) {
    //                 checkedStr = checkedStr + res.data[i].attrValueList[0].attrValue + '/'
    //             } else {
    //                 checkedStr = checkedStr + res.data[res.data.length - 1].attrValueList[0].attrValue
    //             }

    //         }

    //         that.setData({
    //             attrValueList: res.data,
    //             checkedAttr: checkedStr
    //         })
    //     })
    // },


    clickGetDishAttrList(e) {
        let that = this
        let { id, item } = e.currentTarget.dataset
        let tempJson = {
            itemId: id,

        }
        that.setData({
            itemId: id,
            goodsNei: item
        })
        common.post("/item/getDishAttrList", tempJson, function (res) {
            console.log(res,"545466666222222222")
            let checkedStr = '';
            for (let i = 0; i < res.data.length; i++) {
                if (i !== res.data.length - 1) {// 不是最后一个，就拼接/
                    checkedStr = checkedStr + res.data[i].attrValueList[0].attrValue + '/'
                } else {// 最后一个，不拼接/
                    checkedStr = checkedStr + res.data[res.data.length - 1].attrValueList[0].attrValue
                }

            }
            var tempList = res.data;
            for(var i = 0;i < tempList.length;i++){
                var twoList = tempList[i];
                for(var j =0;j < twoList.attrValueList.length;j++){
                    twoList.attrValueList[j].select = false;
                }
            }
            console.log('---checkedStr--',checkedStr);
            that.setData({
                allAttrValueList: tempList,
                checkedAttr: checkedStr
            },()=>{
                console.log('----++====',tempList);
            })
        })
    },


    // 选规格
    go_guige(e) {
        console.log(e, "999900000")
        this.setData({
            guigeShow: true
        }, () => {
            this.clickGetDishAttrList(e)
        })
    },
    onClose() {
        this.setData({
            guigeShow: false
        });
    },
    //购物车减少一
    onminus(e) {
        let item = e.currentTarget.dataset.item
        let cartId = item.id
        this.changeCartNum(-1, cartId, item.itemId)

    },
    //  购物车增加1
    onplus(e) {
        let { index, item } = e.currentTarget.dataset
        let cartId = item.id
        this.changeCartNum(1, cartId, item.itemId)
    },
    //购物车加一
    changeCartNum(num, cartId, itemId) {
        const that = this
        this.setData({
            isShowLoader: true
        })
        let tempJson = {
            itemId: itemId,
            token: that.data.token,
            cartId,
            num,
            userId: that.data.userInfo.id,
        }
        common.wxRequest('/cart/updateOneByCartId', 'POST', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                that.getCartNum()
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },
    // 购物车输入改变
    onblur(e) {
        const that = this
        let { item } = e.currentTarget.dataset
        let num = e.detail.value
        let cartId = item.id
        that.inputCartNum(num, cartId, item.itemId)

    },
    //  输入input改变     userId cartId num   修改数量
    inputCartNum(num, cartId) {
        const that = this
        this.setData({
            isShowLoader: true
        })
        let tempJson = {
            cartId,
            num,
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.wxRequest('/cart/updateNumByCartId', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                that.onCloses()
                that.getCartNum()
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },
    //    立即结算
    go_balance() {
        if (this.data.cartNum == 0) {
            return
        }
        wx.navigateTo({
            url: `/packageC/pages/takeoutOrder/takeoutOrder?storeId=${this.data.storeId}&totalPrice=${this.data.totalPrice}&storeId=${this.data.storeId}`,
        })
    },
    // 购物车关闭
    onCloses() {
        this.setData({
            shopCarShow: false
        })
    },
    // 点击购物车
    click_shoppcar() {
        this.setData({
            shopCarShow: true
        }, () => {
            this.getCartNum()
        })
    },

    // 获取购物车数量
    getCartNum(flag = false) {
        const that = this
        let tempJson = {
            storeId: that.data.storeId,
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.wxRequest('/cart/listByStore', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                let totalPrice = 0;
                let totalNum = res.data.totalNum
                res.data.list.map((item, index) => {
                    totalPrice = item.num * item.price + totalPrice
                })
                that.setData({
                    cartList: res.data.list,
                    cartNum: totalNum,
                    goodsCount: 1,
                    totalPrice
                })

            } else {
                that.setData({
                    cartList: [],
                    cartNum: 0,
                    goodsCount: 1,
                    totalPrice: 0
                })
                if (!flag) {
                    wx.showToast({
                        icon: 'none',
                        title: res.msg ? res.msg : '添加失败',
                    })
                }

            }
        }, () => {
            that.setData({
                isShowLoader: false  //购物车加载
            })
        })
    },
    // tabs切换
    click_item(e) {
        let index = e.currentTarget.dataset.index
        this.setData({
            actIndex: index,
            heightShow: false
        })
    },
    goBack() {
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2]; //上一个页面
        // 从朋友圈进入的时候，页面栈为空，这里需要判断是否有上个页面
        if (prevPage) {
            wx.navigateBack({
                delta: 1
            })
        } else {
            wx.redirectTo({
                url: '/pages/index/index',
            })
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        var that = this
        let capsule = wx.getMenuButtonBoundingClientRect()
        this.setData({
            height: capsule.height,
            top: capsule.top,
        })
        common.getLocalUserInfo(function (success, data) {
            if (success) {
                that.setData({
                    userInfo: data.user,
                    token: data.token,
                    itemId: options.itemId ? options.itemId : 19891,
                    storeId: options.storeId ? options.storeId : 1641
                }, function () {
                    that.getGoodsDes()
                    that.getDataDes() //查询商品详情信息
                    that.getGoodsCommentList() // 获取商品评论
                    that.getPostMethod()
                    this.shopInfo()
                    this.getCartNum(true)
                })
            }
        }, true)
    },
    // 图片预览
    preview(event) {
        let { nindex, windex } = event.currentTarget.dataset
        console.log(nindex, windex)
        let pic_ce = this.data.commentList[windex].picUrls
        this.setData({
            pic_ce,
            current: nindex,
            showImg: true
        })
    },
    // 时间戳
    time(time) {
        return common.dateFormat('yyyy-MM-dd HH:mm', time)
    },
    // 店铺详情
    shopInfo() {
        var that = this
        var tempJson = {
            storeId: that.data.storeId,
            xpoint: this.data.lat,
            ypoint: this.data.lon,
            xcFlag: '0' //是否含有携程门票 0不含有
        }
        common.get('/store/mainPageInfo', tempJson, res => {

            if (res.data.commentList) {
                for (var i = 0; i < res.data.commentList.length; i++) {
                    res.data.commentList[i].addTime = that.time(res.data.commentList[i].addTime)
                }
            }
            this.setData({
                commentList: res.data.commentList,
                shopInfo: res.data
            }, () => {
                // 计算右侧商品高度
                wx.createSelectorQuery().selectAll('.cessss').boundingClientRect(function (rect) {//selectAll会选择所要含有该类名的盒子
                }).exec(function (res) {
                    // that.heightArry(res)
                })
            })
        })
    },
    // 配送方式
    getPostMethod() {
        var that = this
        var tempJson = {
            storeId: that.data.storeId
        };
        common.post("/store/getPostTypeNew", tempJson, function (res) {
            if (res.status === 200) {
                let postType = []
                res.data.map(item => {
                    postType.push(item.dname)
                })
                that.setData({
                    postMethodStr: postType.join(' | ')
                })
            }
        })
    },

    //获取评论列表
    getGoodsCommentList() {
        var that = this
        var tempJson = {
            itemId: that.data.itemId,
            pageNum: '',
            type: 1, //0标识取前2条   1全部数据
            userId: that.data.userInfo.id
        };
        common.post("/comment/getItemCommentlist", tempJson, function (res) {
            console.log(res)
            that.setData({
                commnet: res.data,
                commnetTotalNums: res.data.commnetTotalNums
            })
        })
    },

    //查询商品详情信息
    getDataDes: function () {
        var that = this
        var tempJson = {
            itemId: that.data.itemId,
            // itemId:8102
            // itemId:8313
        }
        common.post("/item/info", tempJson, function (res) {
            if (res.status === 200) {
                //itemAttrList没有数据隐藏商品属性模块 有数据显示遍历
                if (res.data.itemAttrList.length == 0) {
                    that.setData({
                        property: true
                    })
                } else {
                    that.setData({
                        property: false,
                        itemAttrList: res.data.itemAttrList,
                        image: res.data.image,
                        title: res.data.title
                    })
                }
                const richText = res.data.itemDesc ? res.data.itemDesc.replace(/\<img/gi, '<img class="rich-img" ') : ''
                that.setData({
                    Des: res.data,

                    title: res.data.title,
                    storeId: res.data.storeId,
                    goodsInformation: richText,
                    sellPoint: res.data.sellPoint
                }, function () {
                    that.getShopDes(); //店铺信息
                    that.getPostMethod(); // 获取配送方式
                    // that.getshopArrtention(); //是否关注店铺
                })
            } else {
                common.showRequestErrMsg(res)
            }
        }, function () {
            that.setData({
                isLoadingBusy: false
            })
        })
    },
    //查询店铺详情信息
    getShopDes: function () {
        const that = this
        const tempJson = {
            storeId: that.data.storeId
        }
        common.post("/store/info", tempJson, function (res) {
            if (res.status === 200) {
                that.setData({
                    shopData: res.data,
                    storeId: res.data.id
                }, function () {
                    // that.getStoreCoupons(true)
                })
            }
        })
    },
    //查询商品详情信息
    getGoodsDes() {
        const that = this
        let tempJson = {
            itemId: that.data.itemId
        }
        that.setData({
            loadingCount: that.data.loadingCount + 1,
            loadingSuccessCount: that.data.loadingSuccessCount - 1
        }, function () {
            common.post('/item/info', tempJson, function (res) {
                if (res.status === 200) {
                    var storeprice;
                    console.log(app.globalData.discount, "app.globalData.discountapp.globalData.discount")
                    if (that.data.storePriceAddress == -1) {

                        storeprice = app.globalData.cardId ? (app.globalData.productprice) : (res.data.price * app.globalData.discount)
                        // that.getUserAssets()
                    } else {

                        storeprice = that.data.storePriceAddress

                    }
                    that.setData({
                        goodsInfo: res.data,
                        cityBenefitItemFlag: res.data.cityBenefitItemFlag,
                        benefitItemFlag: res.data.benefitItemFlag,
                        storePrice: storeprice,
                        storePriceTwo: app.globalData.cardId ? (app.globalData.productprice) : (res.data.price * app.globalData.discount),
                        price: res.data.price,
                        loadingSuccessCount: that.data.loadingSuccessCount + 1
                        // totalMoney:
                    }, () => {
                        // var isNum =     //是整数，则返回true，否则返回false
                        if (typeof that.data.storePrice == 'number' && that.data.storePrice % 1 == 0) {
                            that.setData({
                                isNum: true
                            })
                        } else {
                            that.setData({
                                isNum: false
                            })
                        }

                    })
                } else {
                    common.showRequestErrMsg(res)
                }
            }, function () {
                that.setData({
                    loadingCount: that.data.loadingCount - 1
                })
            })
        })
    },
    scrollfn(e) {

        wx.createSelectorQuery()
        .select('#scroller')
        .boundingClientRect((res) => {
            // console.log(sc)
          this.setData({
            scrollTop: e.detail.scrollTop,
            offsetTop: res.top,
          });
        })
        .exec();
        // console.log(e,"pp")
        // let query = wx.createSelectorQuery();
        // query.selectAll('#tabs').boundingClientRect((rect) => {
        //     console.log(rect[0].top)
        //     if (this.data.actIndex == 0) {

        //         if (rect[0].top <= 0) {
        //             this.setData({
        //                 heightShow: true
        //             })

        //         } else {

        //             this.setData({
        //                 heightShow: false
        //             })
        //         }
        //     }
        // }).exec();
    },
    click_oneId(e) {
        let that = this
        // console.log('----',e.currentTarget.dataset.item.attrValueList);
        // console.log('----',e.currentTarget.dataset.index);
        // console.log('++++',e.currentTarget.dataset.item[e.currentTarget.dataset.index]);
        // var currentIndex = e.currentTarget.dataset.index;
        // var currentItem = e.currentTarget.dataset.item[currentIndex]


        console.log('----',e.currentTarget.dataset.index);
        console.log('++++',e.currentTarget.dataset.item);

        var currentItem = e.currentTarget.dataset.item;

      
        var tempList = that.data.allAttrValueList;
        for(var i = 0;i < tempList.length;i++){
            var twoList = tempList[i];
            for(var j =0;j < twoList.attrValueList.length;j++){
                // twoList.attrValueList[j].select = false;
                if(twoList.attrValueList[j].id == currentItem.id){
                    if(twoList.attrValueList[j].attrId == currentItem.attrId){
                        for(var m =0;m < twoList.attrValueList.length;m++){
                            twoList.attrValueList[m].select = false;
                        }
                        twoList.attrValueList[j].select = true;
                    }
                    
                }
            }
        }


        if(currentItem.attrId){

        }
        this.setData({
            // allAttrValueList:that.data.allAttrValueList,
            allAttrValueList:tempList,
            oneId:currentItem.id,
        },()=>{
            console.log('oneId---',that.data.oneId);
            console.log('最新---',that.data.allAttrValueList);
        })
        return;
        let {
            couponid
        } = e.currentTarget.dataset
        let tempJson = {
            userId: that.data.userInfo.id,
            discountCouponId: couponid,
            source: 1, // 1为手动领取，2为系统群发
            token: that.data.token
        }

    },
})